package controller.dao;

import model.*;
import java.util.*;
import javax.persistence.*;

public class Dao_Sale {
	EntityManager manager;
	
	public boolean save(Sale sale) {
		try	{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(sale);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public List<Sale> listAll(){
		manager = Factory.factory().createEntityManager();
		manager.getTransaction().begin();
		Query query = (Query) manager.createQuery("SELECT s FROM Sale s" );
		@SuppressWarnings("unchecked")
		List<Sale> Sales =  query.getResultList();
		manager.close();
		return Sales;
	}
	
	public boolean update(Sale sale){
		try{
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.merge(sale);
			manager.getTransaction().commit();
			manager.close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	
	public boolean delete(Sale sale){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			manager.remove(sale);
			manager.getTransaction().commit();
			manager.close();				
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public Sale list(int id){
		try {
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();	
			Sale sale = manager.find(Sale.class, id);
			manager.getTransaction().commit();
			manager.close();
			return sale;
		} catch (Exception e) {
			return null;				
		}
	}
}
